package com.jeeos.framework.security.service;

import com.jeeos.common.constant.AccountMessageConstant;
import com.jeeos.framework.security.domain.JeeosAccount;
import com.jeeos.framework.security.domain.SecurityUser;
import com.jeeos.framework.security.domain.UserDTO;
import com.jeeos.framework.security.mapper.JeeosAccountMapper;
import com.jeeos.framework.utils.ReUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AccountExpiredException;
import org.springframework.security.authentication.CredentialsExpiredException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.LockedException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 用户管理业务类
 * Created by macro on 2020/6/19.
 */
@Service
public class UserServiceImpl implements UserDetailsService {

    private List<UserDTO> userList;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private JeeosAccountMapper jeeosAccountMapper;

    @Override
    public UserDetails loadUserByUsername(String loginName) throws UsernameNotFoundException {
        JeeosAccount jeeosAccount =null;
        if(ReUtils.matchMobile(loginName)){
            jeeosAccount = jeeosAccountMapper.selectByPhoneNumber(loginName);
        }else if(ReUtils.matchEmail(loginName)){
            jeeosAccount = jeeosAccountMapper.selectByEmail(loginName);
        }else{
            jeeosAccount = jeeosAccountMapper.selectByLoginName(loginName);
        }
        if (null==jeeosAccount) {
            throw new UsernameNotFoundException(AccountMessageConstant.USERNAME_PASSWORD_ERROR);
        }
        SecurityUser securityUser = new SecurityUser(jeeosAccount);
        if (!securityUser.isEnabled()) {
            throw new DisabledException(AccountMessageConstant.ACCOUNT_DISABLED);
        } else if (!securityUser.isAccountNonLocked()) {
            throw new LockedException(AccountMessageConstant.ACCOUNT_LOCKED);
        } else if (!securityUser.isAccountNonExpired()) {
            throw new AccountExpiredException(AccountMessageConstant.ACCOUNT_EXPIRED);
        } else if (!securityUser.isCredentialsNonExpired()) {
            throw new CredentialsExpiredException(AccountMessageConstant.CREDENTIALS_EXPIRED);
        }
        return securityUser;
    }


}
